package com.lzb.randomturntable.fragment;

import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lzb.basic.utils.SPUtil;
import com.lzb.randomturntable.BaseNoModelFragment;
import com.lzb.randomturntable.Content;
import com.lzb.randomturntable.R;
import com.lzb.randomturntable.databinding.FragmentRandomNumberBinding;
import com.lzb.randomturntable.adapter.RandomNumberAdapter;
import com.lzb.randomturntable.dialog.CustomSettingDialog;
import com.lzb.randomturntable.dialog.ShowSettingDialog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RandomNumberFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RandomNumberFragment extends BaseNoModelFragment<FragmentRandomNumberBinding> implements View.OnClickListener {

    private RandomNumberAdapter mAdapter;
    private Handler mHandler = new Handler();
    private Runnable mAnimationRunnable;
    private boolean isAnimating = false;
    private int mAnimationDuration;
    private int mMinValue;
    private int mMaxValue;
    private int mNumberAmount;
    private boolean mAllowRepeat;
    private boolean mIsOrderResult;

    @Override
    protected int onCreate() {
        return R.layout.fragment_random_number;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSetting.setOnClickListener(this);
        mDataBinding.ivEdit.setOnClickListener(this);
        mDataBinding.tvGenerate.setOnClickListener(this);

        mDataBinding.rvNumberList.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new RandomNumberAdapter();
        mDataBinding.rvNumberList.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivSetting) {//展示设置
            showShowSettingDialog();
        } else if (id == R.id.ivEdit) {//自定义设置
            showCustomSettingDialog();
        } else if (id == R.id.tvGenerate) {//生成随机数
            generateRandomNumbers();
        }
    }

    @Override
    protected void initData() {
        loadSettings();
        updateScopeText();
    }

    private void loadSettings() {
        mAnimationDuration = SPUtil.getInt(mContext, Content.randomNumberDuration, 2) * 1000;
        mMinValue = SPUtil.getInt(mContext, Content.randomNumberMin, 1);
        mMaxValue = SPUtil.getInt(mContext, Content.randomNumberMax, 100);
        mNumberAmount = SPUtil.getInt(mContext, Content.randomNumberAmount, 1);
        mAllowRepeat = SPUtil.getBoolean(mContext, Content.isRandomNumberRepeat, false);
        mIsOrderResult = SPUtil.getBoolean(mContext, Content.isOrderResult, false);
    }

    private void updateScopeText() {
        String scopeText = String.format("%d~%d", mMinValue, mMaxValue);
        mDataBinding.tvScope.setText(scopeText);
    }

    private void generateRandomNumbers() {
        if (isAnimating) {
            stopAnimation();
            return;
        }

        // 生成最终的随机数列表
        List<Integer> finalNumbers = generateFinalNumbers();

        if (finalNumbers.isEmpty()) {
            return;
        }

        // 如果是单个数字，显示在tvSingle上
        if (mNumberAmount == 1) {
            showSingleNumber(finalNumbers.get(0));
        } else {
            // 多个数字显示在RecyclerView上
            showMultipleNumbers(finalNumbers);
        }
    }

    private List<Integer> generateFinalNumbers() {
        List<Integer> numbers = new ArrayList<>();
        Random random = new Random();

        if (mAllowRepeat) {
            // 允许重复
            for (int i = 0; i < mNumberAmount; i++) {
                numbers.add(random.nextInt(mMaxValue - mMinValue + 1) + mMinValue);
            }
        } else {
            // 不允许重复
            if (mNumberAmount > (mMaxValue - mMinValue + 1)) {
                // 如果数量超过范围，调整到最大值
                mNumberAmount = mMaxValue - mMinValue + 1;
            }

            Set<Integer> uniqueNumbers = new HashSet<>();
            while (uniqueNumbers.size() < mNumberAmount) {
                uniqueNumbers.add(random.nextInt(mMaxValue - mMinValue + 1) + mMinValue);
            }
            numbers.addAll(uniqueNumbers);
        }

        // 按顺序显示结果
        if (mIsOrderResult) {
            Collections.sort(numbers);
        }

        return numbers;
    }

    private void showSingleNumber(final int finalNumber) {
        mDataBinding.tvSingle.setVisibility(View.VISIBLE);
        mDataBinding.rvNumberList.setVisibility(View.GONE);

        startNumberAnimation(mDataBinding.tvSingle, finalNumber);
    }

    private void showMultipleNumbers(final List<Integer> finalNumbers) {
        mDataBinding.tvSingle.setVisibility(View.GONE);
        mDataBinding.rvNumberList.setVisibility(View.VISIBLE);

        // 创建动画数字列表
        List<String> animationNumbers = new ArrayList<>();
        for (int i = 0; i < mNumberAmount; i++) {
            animationNumbers.add(String.valueOf(mMinValue));
        }

        mAdapter.setList(animationNumbers);

        // 开始动画
        startListAnimation(finalNumbers);
    }

    private void startNumberAnimation(final TextView textView, final int finalNumber) {
        isAnimating = true;
        mDataBinding.tvGenerate.setText(R.string.stop);

        final long startTime = System.currentTimeMillis();
        final Random random = new Random();

        mAnimationRunnable = new Runnable() {
            @Override
            public void run() {
                long currentTime = System.currentTimeMillis();
                long elapsedTime = currentTime - startTime;

                if (elapsedTime < mAnimationDuration) {
                    // 动画进行中，显示随机数
                    int randomNum = random.nextInt(mMaxValue - mMinValue + 1) + mMinValue;
                    textView.setText(String.valueOf(randomNum));

                    // 继续动画
                    mHandler.postDelayed(this, 50);
                } else {
                    // 动画结束，显示最终数字
                    textView.setText(String.valueOf(finalNumber));
                    stopAnimation();
                }
            }
        };

        mHandler.post(mAnimationRunnable);
    }

    private void startListAnimation(final List<Integer> finalNumbers) {
        isAnimating = true;
        mDataBinding.tvGenerate.setText(R.string.stop);

        final long startTime = System.currentTimeMillis();
        final Random random = new Random();

        mAnimationRunnable = new Runnable() {
            @Override
            public void run() {
                long currentTime = System.currentTimeMillis();
                long elapsedTime = currentTime - startTime;

                if (elapsedTime < mAnimationDuration) {
                    // 动画进行中，更新所有数字
                    List<String> animationNumbers = new ArrayList<>();
                    for (int i = 0; i < mNumberAmount; i++) {
                        int randomNum = random.nextInt(mMaxValue - mMinValue + 1) + mMinValue;
                        animationNumbers.add(String.valueOf(randomNum));
                    }
                    mAdapter.setList(animationNumbers);

                    // 继续动画
                    mHandler.postDelayed(this, 50);
                } else {
                    // 动画结束，显示最终数字
                    List<String> finalNumberStrings = new ArrayList<>();
                    for (Integer number : finalNumbers) {
                        finalNumberStrings.add(String.valueOf(number));
                    }
                    mAdapter.setList(finalNumberStrings);
                    stopAnimation();
                }
            }
        };

        mHandler.post(mAnimationRunnable);
    }

    private void stopAnimation() {
        isAnimating = false;
        mDataBinding.tvGenerate.setText(R.string.generate_random_number);

        if (mAnimationRunnable != null) {
            mHandler.removeCallbacks(mAnimationRunnable);
            mAnimationRunnable = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopAnimation();
    }

    private void showShowSettingDialog() {
        ShowSettingDialog dialog = new ShowSettingDialog(mContext);
        dialog.setListener(new ShowSettingDialog.Ilistener() {
            @Override
            public void clickCancel() {
                loadSettings();
            }
        });
        dialog.show();
    }

    private void showCustomSettingDialog() {
        CustomSettingDialog dialog = new CustomSettingDialog(mContext);
        dialog.setListener(new CustomSettingDialog.Ilistener() {
            @Override
            public void clickConfirm() {
                // 设置确认后的回调，重新加载设置
                loadSettings();
                updateScopeText();
            }
        });
        dialog.show();
    }

}